/*
 * Copyright © 2004-2014 chenYuan. All rights reserved.
 * @Website:wwww.jspx.net
 * @Mail:39793751@qq.com
 * @author: chenYuan , 陈原
 * @License: Jspx.net Framework Code is open source (LGPL)，Jspx.net Framework 使用LGPL 开源授权协议发布。
 * @jvm:jdk1.6+  x86/amd64
 *
 */
package com.jspx.txweb.dao.impl;

import com.jspx.sober.criteria.expression.InExpression;
import com.jspx.utils.ArrayUtil;
import com.jspx.utils.DateUtil;
import com.jspx.txweb.dao.VoteDAO;
import com.jspx.txweb.table.vote.VoteItem;
import com.jspx.txweb.table.vote.VoteMember;
import com.jspx.txweb.table.vote.VoteTopic;
import com.jspx.utils.StringUtil;
import com.jspx.sober.jdbc.JdbcOperations;
import com.jspx.sober.criteria.expression.Expression;
import com.jspx.sober.criteria.projection.Projections;
import com.jspx.sober.criteria.Order;
import com.jspx.sober.Criteria;
import com.jspx.sober.ssql.SSqlExpression;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.sql.SQLException;
import java.util.List;
import java.util.ArrayList;
import java.util.Date;


/**
 * Created by IntelliJ IDEA.
 * User:chenYuan (mail:39793751@qq.com)
 * Date: 2006-2-28
 * Time: 17:23:13
 * jspx.service.vote.impl.VoteDAOImpl
 */
public class VoteDAOImpl extends JdbcOperations implements VoteDAO
{
    final private static Logger log = LoggerFactory.getLogger(VoteDAOImpl.class);
    private String namespace = StringUtil.empty;

    public VoteDAOImpl()
    {

    }

    public void setNamespace(String namespace)
    {
        this.namespace = namespace;
    }

    public String getNamespace()
    {
        return namespace;
    }


    /**
     * 得到一个投票的投票总数
     *
     * @param topicId  投票id
     * @return int
     */
    public int getSumVotePoint(long topicId)
    {
        if (topicId <0) return 1;
        int x = (Integer) createCriteria(VoteItem.class)
                .add(Expression.eq("topicId", topicId))
                .setProjection(Projections.sum("votePoint")).uniqueResult();
        if (x <= 0) return 1;
        return x;
    }

    /**
     *
     *
     * @param topicId  主题id
     * @param uid  用户id
     * @return boolean 判断是否已经投票
     */
    public boolean isVoted(long topicId, long uid,String unionid)
    {
        if (topicId <= 0 || uid<=0) return true;
        Criteria criteria = createCriteria(VoteMember.class);
        if (!StringUtil.isNULL(unionid))
        {
            criteria = criteria.add(Expression.eq("unionid", unionid));
        } else
            criteria = criteria.add(Expression.or(Expression.eq("putUid", uid),Expression.eq("unionid", unionid)));

        return criteria.add(Expression.eq("topicId", topicId))
                .setProjection(Projections.rowCount()).intUniqueResult()>0;
    }

    /**
     * @param topicId 主题id
     * @param ip ip
     * @param system  系统
     * @param browser  浏览器
     * @param openId  微信用户id
     * @param day  几天以内算一次
     * @return  判断是否已经投票
     */
    public int getGuestVoteCount(long topicId, String ip,String system,String browser,String openId,String unionid,int day)
    {
        if (topicId == 0 || ip==null|| browser==null|| system==null) return 0;
        Date startDate = DateUtil.getStartDateTime(DateUtil.addDate(-day)); //一天内
        if (!StringUtil.isNULL(openId))
        {
            //普通方式判断
            Criteria criteria = createCriteria(VoteMember.class).add(Expression.gt("createDate", startDate))
                    .add(Expression.eq("topicId", topicId));
            if (!StringUtil.isNULL(unionid))
                criteria = criteria.add(Expression.eq("unionid", unionid));
            else
                criteria.add(Expression.eq("ip", ip)).add(Expression.eq("openId", openId));
            return  criteria.setProjection(Projections.rowCount()).intUniqueResult();
        } else  if (!StringUtil.isNULL(unionid))
        {
            //普通方式判断
            Criteria criteria = createCriteria(VoteMember.class).add(Expression.gt("createDate", startDate)).add(Expression.eq("unionid", unionid));
            return  criteria.setProjection(Projections.rowCount()).intUniqueResult();
        } else
        {
            return createCriteria(VoteMember.class)
                    .add(Expression.eq("topicId", topicId))
                    .add(Expression.eq("ip", ip))
                    .add(Expression.eq("browser", browser))
                    .add(Expression.eq("system", system))
                    .add(Expression.gt("createDate", startDate))
                    .setProjection(Projections.rowCount()).intUniqueResult();
        }
    }

    /**
     *
     *
     * @param topicId 得到ID定影的投票
     * @return VoteTopic
     */
    public VoteTopic getVoteTopic(long topicId) throws SQLException {
        return (VoteTopic) get(VoteTopic.class, topicId, true);
    }

    /**
     *
     *
     * @param parentId 得到ID定影的投票
     * @return VoteTopic
     */
    public VoteTopic getVoteTopicForParentId(long parentId)
    {
        return (VoteTopic)createCriteria(VoteTopic.class).add(Expression.eq("parentId", parentId)).add(Expression.eq("namespace", namespace)).objectUniqueResult(true);
    }


    /**
     * 得到第一个投票
     * @return VoteTopic
     */
    public VoteTopic getFirstVoteTopic(String groupId)
    {
        Criteria criteria = createCriteria(VoteTopic.class).add(Expression.eq("namespace", namespace));
        if (!StringUtil.isNULL(groupId) && !"*".equals(groupId))
        {
            criteria = criteria.add(Expression.eq("groupId", groupId));
        }
        VoteTopic v = (VoteTopic) criteria.addOrder(Order.desc("sortType"))
                .addOrder(Order.desc("sortDate"))
                .addOrder(Order.desc("createDate"))
                .objectUniqueResult(true);
        if (v == null)
        {
            v = new VoteTopic();
            v.setTopicText("NO Vote");
        }
        return v;
    }


    /**
     * 得到投票列表
     *
     * @param topicId 主题id
     * @return List
     */
    @SuppressWarnings("unchecked")
    public List<VoteItem> getVoteList(long topicId)
    {
        if (topicId == 0) return new ArrayList<VoteItem>();
        return (List<VoteItem>) createCriteria(VoteItem.class).add(Expression.eq("namespace", namespace)).add(Expression.eq("topicId", topicId))
                .addOrder(Order.asc("sortType")).list(false);
    }

    /**
     *
      * @param voteIds 投票
     * @return boolean
     */
    public boolean postVote(Long[] voteIds) throws Exception
    {
        if (voteIds == null || voteIds.length <= 0) return false;
        InExpression inExpression = new InExpression(getSoberTable(VoteItem.class).getPrimary(),voteIds);
        String SQL = "UPDATE "+getSoberTable(VoteItem.class).getTableName()+" SET votePoint=votePoint+1 WHERE "+ inExpression.toSqlString(getSoberTable(VoteItem.class),getSoberFactory().getDatabaseName());
        return update(SQL,inExpression.getParameter(getSoberTable(VoteItem.class)))>=0;
    }

    /**
     * 删除
     *
     * @param topicId 主题id
     * @return boolean
     */

    public boolean deleteVote(long topicId)
    {
        if (topicId<=0) return false;
        try
        {
            /////////////删除投票begin
            super.delete(VoteTopic.class, topicId,true);
            /////////////删除投票end

            /////////////删除投票选项begin
            super.delete(VoteItem.class, "topicId", topicId);
            /////////////删除投票选项end
        }
        catch (Exception e)
        {
            return false;
        }
        return true;
    }

    public boolean deleteVote(Long[] topicIds)
    {
        if (null == topicIds) return false;
        try
        {
            for (long topicId : topicIds)
            {
                if (topicId<=0) continue;
                /////////////删除投票begin
                super.delete(VoteTopic.class, topicId,true);
                /////////////删除投票end

                /////////////删除投票的人begin
                super.delete(VoteMember.class, "topicId", topicId);
                /////////////删除投票的人end

                /////////////删除投票选项begin
                super.delete(VoteItem.class, "topicId", topicId);
                /////////////删除投票选项end
            }
        }
        catch (Exception e)
        {
            log.error(ArrayUtil.toString(topicIds, StringUtil.COMMAS),e);
            return false;
        }
        return true;
    }

    /**
     * 排序
     *
     * @param topicIds 主题id
     * @param sortType  排序
     * @return boolean
     */

    public boolean updateSortType(Long[] topicIds, int sortType)
    {
        if (null == topicIds) return true;
        try
        {
            for (long topicId : topicIds)
            {
                if (topicId<=0) continue;
                VoteTopic votetopic = (VoteTopic) get(VoteTopic.class, topicId);
                if (votetopic == null) continue;
                votetopic.setSortType(sortType);
                super.update(votetopic, new String[]{"sortType"});
            }

        }
        catch (Exception e)
        {
            log.error(ArrayUtil.toString(topicIds, StringUtil.COMMAS),e);
            return false;
        }
        return true;
    }

    /**
     * 提前
     *
     * @param topicIds 主题id
     * @return boolean
     */
    public boolean updateSortDate(Long[] topicIds)
    {
        if (null == topicIds) return true;
        try
        {
            for (long topicId : topicIds)
            {
                if (topicId<=0) continue;
                VoteTopic votetopic = (VoteTopic) get(VoteTopic.class, topicId);
                if (votetopic == null) continue;
                votetopic.setSortDate(new Date());
                update(votetopic, new String[]{"sortDate"});
            }

        }
        catch (Exception e)
        {
            log.error(ArrayUtil.toString(topicIds, StringUtil.COMMAS),e);
            return false;
        }
        return true;
    }

    /**
     * @param find       查询字符串 "" 自动分开查询
     * @param sortString 排序字符串
     * @param term       特别情况标记  0 不管   1 查询有图片的 2 查询无图片的  3 查询有下载文件的   4 查询无下载文件的  5 查询有图片的
     * @param ipage      页数
     * @param count      返回数量
     *                   String groupId    分组
     * @return List<VoteTopic>
     */
    @SuppressWarnings("unchecked")
    public List<VoteTopic> getList(
            String find,
            String term,
            String sortString,
            long uid,
            String groupId,
            int ipage, int count) throws Exception
    {
        Criteria criteria = createCriteria(VoteTopic.class).add(Expression.eq("namespace", namespace));
        if (!StringUtil.isNULL(find))
        {
            criteria = criteria.add(Expression.like("topicText", "%" + find + "%"));
        }
        if (uid>0)
        {
            criteria = criteria.add(Expression.eq("putUid", uid));
        }
        if (!StringUtil.isNULL(groupId) && !"*".equals(groupId))
        {
            criteria = criteria.add(Expression.eq("groupId", groupId));
        }
        criteria = SSqlExpression.getTermExpression(criteria, term);
        criteria = SSqlExpression.getSortOrder(criteria, sortString);
        return (List<VoteTopic>) criteria.setCurrentPage(ipage).setTotalCount(count).list(false);
    }


    /**
     *
     *
     * @param find 得到记录条数
     * @return int
     */
    public int getCount(
            String find,
            String term,
            long uid,
            String groupId
    ) throws Exception
    {
        Criteria criteria = createCriteria(VoteTopic.class).add(Expression.eq("namespace", namespace));
        if (!StringUtil.isNULL(find))
        {
            criteria = criteria.add(Expression.like("topicText", "%" + find + "%"));
        }
        if (uid>0)
        {
            criteria = criteria.add(Expression.eq("putUid", uid));
        }
        if (!StringUtil.isNULL(groupId) && !"*".equals(groupId))
        {
            criteria = criteria.add(Expression.eq("groupId", groupId));
        }
        criteria = SSqlExpression.getTermExpression(criteria, term);
        return criteria.setProjection(Projections.rowCount()).intUniqueResult();
    }
    //------------------------------------------------------------------------------------------------------------------

    /**
     *  投票搜索
     * @param tid
     * @param id
     * @param find
     * @param term
     * @param sortString
     * @param page
     * @param count
     * @return 投票选项列表
     * @throws Exception
     */
    @SuppressWarnings("unchecked")
    public List<VoteItem> getItemList(
            long tid,
            long id,
            String find,
            String term,
            String sortString,
            int page, int count) throws Exception
    {
        Criteria criteria = createCriteria(VoteItem.class).add(Expression.eq("topicId", tid));
        if (!StringUtil.isNULL(find))
        {
            criteria = criteria.add(Expression.like("title", "%" + find + "%"));
        }
        if (id>0)
        {
            criteria = criteria.add(Expression.eq("id", id));
        }
        criteria = SSqlExpression.getTermExpression(criteria, term);
        criteria = SSqlExpression.getSortOrder(criteria, sortString);
        return (List<VoteItem>) criteria.setCurrentPage(page).setTotalCount(count).list(false);
    }

    public int getItemCount(
            long tid,
            long id,
            String find,
            String term
    ) throws Exception
    {
        Criteria criteria = createCriteria(VoteItem.class).add(Expression.eq("topicId", tid));
        if (!StringUtil.isNULL(find))
        {
            criteria = criteria.add(Expression.like("title", "%" + find + "%"));
        }
        if (id>0)
        {
            criteria = criteria.add(Expression.eq("id", id));
        }
        criteria = SSqlExpression.getTermExpression(criteria, term);
        return  criteria.setProjection(Projections.rowCount()).intUniqueResult();
    }
}